package com.patterns.cor;

import java.util.ArrayList;
import java.util.List;

/**
 * 责任链模式
 * @author fwj
 * @date 2021/4/21 17:01
 **/
public class Main {
    public static void main(String[] args) {
        Msg msg = new Msg();
        msg.setMsg("hello world。 <script> ; hello design patterns. 996 ICU; www.123.com");

        System.out.println(msg.getMsg());

        FilterChain filterChain = new FilterChain();
        filterChain.add(new HtmlFilter())
                .add(new SensitiveFilter());

        FilterChain f2 = new FilterChain()
                .add(new HelloFilter())
                .add(new UrlFilter());

        filterChain.add(f2);

        filterChain.doFilter(msg);

        System.out.println(msg.getMsg());
    }
}

class Msg {
    String name;
    String msg;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public String toString() {
        return "Msg{" +
                "msg='" + msg + '\'' +
                '}';
    }
}

interface Filter {
    boolean doFilter(Msg msg);
}

class HtmlFilter implements Filter {
    @Override
    public boolean doFilter(Msg msg) {
        String r = msg.getMsg();
        r = r.replace("<", "[");
        r = r.replace(">", "]");

        msg.setMsg(r);
        return true;
    }
}

class SensitiveFilter implements Filter {
    @Override
    public boolean doFilter(Msg msg) {
        String r = msg.getMsg();
        r = r.replace("996", "955");
        msg.setMsg(r);
        return false;
    }
}

class HelloFilter implements Filter {

    @Override
    public boolean doFilter(Msg msg) {
        String r = msg.getMsg();
        r = r.replace("hello", "^v^");
        msg.setMsg(r);
        return true;
    }
}

class UrlFilter implements Filter {

    @Override
    public boolean doFilter(Msg msg) {
        String r = msg.getMsg();
        r = r.replace("www.123.com", "www.gitee.com");
        msg.setMsg(r);
        return true;
    }
}

class FilterChain implements Filter{
    List<Filter> filters = new ArrayList<>();

    public FilterChain add(Filter filter) {
        filters.add(filter);
        return this;
    }

    public boolean doFilter(Msg msg) {
        for (Filter filter : filters) {
            if (!filter.doFilter(msg)) return false;
        }
        return true;
    }
}